package xyz.luhui1hao.rxjava2andretrofit2;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import xyz.luhui1hao.rxjava2andretrofit2.api.http.ApiMethods;
import xyz.luhui1hao.rxjava2andretrofit2.api.observer.ObserverOnNextListener;
import xyz.luhui1hao.rxjava2andretrofit2.api.progress.ProgressObserver;
import xyz.luhui1hao.rxjava2andretrofit2.utils.JsonFormatUtil;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.content_tv)
    TextView contentTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn1, R.id.btn2, R.id.btn3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn1:
                baseUrlRequest();
                break;
            case R.id.btn2:
                doubanRequest();
                break;
            case R.id.btn3:
                doubanRequestGet();
                break;
        }
    }

    private void baseUrlRequest(){
        ApiMethods.baseUrlRequest(new ProgressObserver<ResponseBody>(this, listener));
    }

    private void doubanRequest(){
        ApiMethods.doubanRequest(new ProgressObserver<ResponseBody>(this, listener2), 25, 25);
    }

    private void doubanRequestGet(){
        ApiMethods.doubanRequestGet(new ProgressObserver<ResponseBody>(this, listener2), 25, 25);
    }

    ObserverOnNextListener<ResponseBody> listener = new ObserverOnNextListener<ResponseBody>() {

        @Override
        public void onNext(ResponseBody responseBody) {
            try {
                String content = responseBody.string().trim();
                contentTv.setText(content);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    ObserverOnNextListener<ResponseBody> listener2 = new ObserverOnNextListener<ResponseBody>() {

        @Override
        public void onNext(ResponseBody responseBody) {
            try {
                String content = responseBody.string().trim();
                contentTv.setText(JsonFormatUtil.formatJson(content));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
}
